#include <opencv/cv.h>
#include <opencv2/opencv.hpp>
#include <opencv/cxcore.h>
#include <opencv/highgui.h>
#include <stdlib.h>
#include <stdio.h>

#include "cnats.h"
#include "clog.h"
#include "threads.h"

using namespace std;


int main(int argc, char const *argv[]){
    clog::setLevel(2);
    clog::il("Start");
    CvCapture* pCapture = cvCreateCameraCapture(0);
    IplImage* pFrame = NULL;
    vector<unsigned char> buf;
    cnats* conn = cnats::Connect("nats://localhost:4222");
    while(1){
        pFrame=cvQueryFrame( pCapture );
        if(!pFrame){
            printf("Error Read Frame\n");
            continue;
        }
        cv::Mat img = cv::cvarrToMat(pFrame);
        if (!cv::imencode(".jpg",img,buf) ){
            printf("Error Encode to jpg\n");
        }else{
            printf("Code length %lu\n", buf.size());
        }
        if (!cv::imencode(".jpg",img,buf) ){
            printf("Error Encode to jpg\n");
        }else{
            printf("Code length %lu\n", buf.size());
        }        
        conn->Publish(string("Img"), (char *)buf.data(), buf.size(), NULL);
    }
    return 0;
}